<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 目标名称、状态搜索框 -->
        <el-form :inline="true" class="demo-form-inline">
          <el-row type="flex" justify="space-between" align="middle">
            <el-col>
              <el-form-item label="关键字" prop="keyword">
                <el-input v-model="form.keyword" placeholder="根据文章标题搜索"></el-input>
              </el-form-item>
              <el-form-item label="状态" prop="state">
                <el-select placeholder="请选择" v-model="form.state">
                  <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click='clearable'>清除</el-button>
                <el-button type="primary" @click="goSearch">搜索</el-button>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item>
                <el-button @click="openDrawer('add')" style="background:#67c23a; color:#fff">新增技巧</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 警告栏 -->
        <el-alert type="info" class="alert" :closable="false" show-icon>数据一共{{counts }}条</el-alert>

        <!-- 表格 -->
        <el-table :data="tableData" style="width: 100%">
          <el-table-column label="序号" width="50">
            <template slot-scope="{$index}">{{ $index + 1 }}</template>
          </el-table-column>
          <el-table-column prop="title" label="文章标题" width="380">
            <template #default="{ row }">
              {{ row.title }}
              <el-link v-if="row.videoURL" icon="el-icon-film" type="primary"
                @click="videoPreview(row.videoURL)"></el-link>
            </template>
          </el-table-column>
          <el-table-column prop="visits" label="阅读数" width="100">
          </el-table-column>
          <el-table-column prop="username" label="录入人">
          </el-table-column>
          <el-table-column :formatter="repaced" prop="createTime" label="录入时间">

          </el-table-column>
          <el-table-column prop="state" label="状态" width="100">
            <template slot-scope="scope">
              <!-- <span v-if="data.row.state == 1">已启用</span>
              <span v-else>已禁用</span> -->
              {{ scope.row.state ? '已启用' : '已禁用' }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button @click="openDrawer('preview', row.id)" type="text">预览</el-button>
              <el-button type="text" @click="doAllow(row)">
                <template #default v-if="row.state === 1"> 禁用 </template>
                <template #default v-else>启用 </template>
              </el-button>
              <el-button type="text" @click="openDrawer('edit', row.id)" :disabled="row.state === 1">修改</el-button>
              <el-button type="text" @click="dodDel(row.id)" :disabled="row.state === 1">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="block">
          <el-pagination  hide-on-single-page  background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryParams.page" :page-sizes="[5, 10, 20, 50]" :page-size="queryParams.pagesize"
            layout=" prev, pager, next,  sizes,jumper" :total="counts">
          </el-pagination>
        </div>
      </el-card>
      <!-- 模态框 -->
      <el-dialog :title="drawerTitle" :visible.sync="dialogFormVisible">
        <!-- 新增和编辑的模态框 -->
        <el-form :model="addForm" :rules="rules" ref="addForm" label-width="80px" :visible.sync="dialogFormVisible"
          @close="btnCancel">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="addForm.title" placeholder="请输入文章标签"></el-input>
          </el-form-item>
          <el-form-item label="文章内容" prop="articleBody">
            <quill-editor v-model="addForm.articleBody" @blur="$refs.addForm.validateField('articleBody')">
            </quill-editor>
          </el-form-item>
          <el-form-item label="视频地址" prop="videoURL">
            <el-input v-model="addForm.videoURL" placeholder="请输入视频地址"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addFn">确认</el-button>
            <el-button @click="btnCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 预览模态框 -->
      <el-dialog :title="drawerTitle" :visible.sync="previewFormVisible" width="52%">
        <div>
          <h3>{{ previewForm.title }}</h3>
          <div>
            <span>{{ previewForm.createTime }}</span>
            <span>超级管理员</span>
            <span>{{ previewForm.videoURL }}</span>
            <span>{{ previewForm.visits }}</span>
          </div>
          <div v-html="previewForm.articleBody"></div>
        </div>
      </el-dialog>
      <!-- 图标 -->
      <div class="videomasks" v-show="videoState"
        style="position: absolute;top: 0;width: 100%;height: 100%;text-align: center;">
        <div class="btnClose">
          <el-button type="info" icon="el-icon-close" circle @click="videoState = false"></el-button>
        </div>
        <video :src="videoSrc" controls="controls" autoplay width="100%" height="100%">
        </video>
      </div>
    </div>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { list, remove, changeState, detail, add, update } from '@/api/hmmm/articles'
import { status } from '@/api/hmmm/constants'

export default {

  data () {
    return {
      videoState: false,
      videoSrc: '',
      drawerType: 'add',
      previewFormVisible: false, // 预览关闭
      dialogFormVisible: false, // 编辑和新增
      tableData: [], // 列表
      // 状态
      form: {
        state: null, // 状态
        keyword: '' // 输入框
      },
      counts: 0, // 记录总数
      // 分页
      queryParams: {
        page: 1, // 当前页码
        pages: 1, // 总页数
        pagesize: 10 // 页大小
      },

      // 预览
      previewForm: {
        title: '', // 标题
        articleBody: '', // 文章正文
        videoURL: '', // 视频地址
        visits: '', // 阅读数
        createTime: '' // 时间
      },

      // 新增和修改
      addForm: {
        title: '', // 标题
        articleBody: '', // 文章正文
        videoURL: '' // 视频地址
      },

      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      }

    }
  },

  components: {
    quillEditor
  },

  created () {
    this.getArticlesList() // 渲染列表
  },

  computed: {
    // 状态
    status () {
      return status
    },

    // 标题
    drawerTitle () {
      let title = '标题'
      if (this.drawerType === 'add') title = '添加文章'
      if (this.drawerType === 'preview') title = '预览文章'
      if (this.drawerType === 'edit') title = '修改文章'
      return title
    }
  },

  methods: {
    // 时间
    // 行、 列 、参数 、 索引
    repaced (row, column, cellValue, index) {
      return cellValue.replace('T', ' ').substring(0, 19)
    },
    // 图标
    videoPreview (videoURL) {
      this.videoState = true
      this.videoSrc = videoURL
    },

    masksCloseFun () {
      this.videoState = false
    },

    // 每页条数
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.page = 1
      this.getArticlesList()
    },

    // 当前页
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.getArticlesList()
    },

    // 预览
    async Preview (id) {
      // this.dialogFormVisible = true
      const res = await detail({ id })
      console.log(res)
      this.previewForm = res.data
    },

    //  打开抽屉
    async openDrawer (type, id) {
      if (type === 'edit') {
        this.Preview(id)
        this.drawerId = id
        this.drawerType = type
        this.dialogFormVisible = true

        const res = await detail({ id })
        this.addForm = {
          ...res.data
        }
      }
      if (type === 'preview') {
        console.log('点击')
        this.Preview(id)
        this.drawerId = id
        this.drawerType = type
        this.previewFormVisible = true
      }

      if (type === 'add') {
        this.drawerType = type
        this.dialogFormVisible = true
      }
    },

    // 确认按钮
    async addFn () {
      // 新增
      if (this.drawerType === 'add') {
        // 表单校验（对整个表单校验）
        await this.$refs.addForm.validate()
        // 发送请求
        await add(this.addForm)
        // 重置页码
        this.current = 1
        // 提示用户
        this.$message.success('添加成功')
        // 重新渲染
        this.getArticlesList()
        // 抽屉关闭
        this.dialogFormVisible = false
        // 重置表单
        this.btnCancel()
        // console.log(res)
      }

      // 修改
      if (this.drawerType === 'edit') {
        // 校验（对整个表单校验）
        await this.$refs.addForm.validate()
        const res = await update(this.addForm)
        console.log(res.data)
        // 抽屉关闭
        this.dialogFormVisible = false
        // 3.提示用户
        this.$message.success('修改成功')
        // 重新渲染
        this.getArticlesList()
        // 重置页码
        this.current = 1
        // 重置表单
        this.btnCancel()
      }
    },
    // 1.把关闭和重置功能 封装到单独的方法中
    // 2.添加成功后，调用关闭方法
    // 取消按钮
    btnCancel () {
      this.addForm = {
        title: '', // 标题
        articleBody: '', // 文章正文
        videoURL: '' // 视频地址
      }

      this.$refs.addForm.resetFields() // 将数据重置
      this.dialogFormVisible = false
    },

    // 点击启用按钮
    async doAllow (row) {
      console.log(row) // 禁用0, 启用1
      // 取反
      const state = row.state ? 0 : 1
      // 发送请求更改数据
      await changeState({ state, id: row.id })
      // 重新渲染数据
      this.getArticlesList()
    },

    // 删除弹框
    async dodDel (id) {
      console.log(id)
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // // 删除请求
        await remove({ id })
        this.getArticlesList()
        // 删除成功的提示
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },

    // 搜索
    goSearch () {
      console.log('进行了搜索,搜索历史更新')
      this.getArticlesList() // 渲染列表
    },

    // 清除按钮
    clearable () {
      this.form.keyword = ''
    },

    // 渲染列表
    async getArticlesList () {
      const res = await list(
        {
          page: this.page,
          pagesize: this.pageSize,
          keyword: this.form.keyword,
          state: this.form.state
        }
      )
      console.log(res.data.items)
      this.tableData = res.data.items
      this.counts = res.data.counts
    }

  }
}

</script>

<style scoped>
.block {
  margin-top: 20px;
  text-align: right;
}
</style>
